package com.rpcdemo.rpc.transport;

import com.rpcdemo.rpc.Dispatcher;
import com.rpcdemo.rpc.protocol.MyContent;
import com.rpcdemo.util.SeriaUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyHttpServlet extends HttpServlet {

    Dispatcher dispatcher = Dispatcher.getDispatcher();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.toString());

        ServletInputStream is = req.getInputStream();

        ObjectInputStream ois = new ObjectInputStream(is);

        try {
            MyContent myContent = (MyContent)ois.readObject();

            String clazz = myContent.getName();
            String methodName = myContent.getMethodName();
            Class<?>[] parameterTypes = myContent.getParameterTypes();
            Object[] args = myContent.getArgs();

            Object impl = dispatcher.get(clazz);

            Class<?> implClass = impl.getClass();
            Object res = null;
            try {
                Method method = implClass.getMethod(methodName, parameterTypes);
                res = method.invoke(impl, args);

            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }

            MyContent respBody = new MyContent();
            respBody.setRes(res);

            ServletOutputStream os = resp.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(respBody);


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
}
